package com.lzl.producer.filter;

import com.lzl.common.GateWayPo;
import com.lzl.common.http.SimpleRequest;
import com.lzl.common.http.SimpleResponse;
import com.lzl.producer.Producer;
import com.lzl.producer.services.ProducerService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "GateWayFilter", urlPatterns = "/*")
public class GateWayFilter implements Filter {

    @Autowired
    Producer producer;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (httpServletRequest.getRequestURL().indexOf(".") > -1) {
            chain.doFilter(request, response);
            return;
        }
        SimpleRequest simpleRequest = getSimpleRequest(httpServletRequest);
        GateWayPo po = new GateWayPo(simpleRequest);

        boolean falg = producer.submit(po);
        if (falg) {
            try {
                boolean await = po.await(1L);
                System.out.println("等待结果：" + await);
                if (await) {
                    SimpleResponse simpleResponse = po.getResponse();
                    if (simpleResponse == null) {
                        result(response, "无响应".getBytes());
                    } else {
                        result(response, simpleResponse.getContent().getBytes());
                    }
                } else {
                    result(response, "请求超时".getBytes());
                }
            } catch (Exception e) {
                e.printStackTrace();
                result(response, "请求超时".getBytes());
            }
        }

    }

    private void result(ServletResponse response, byte[] bytes) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(bytes);
    }

    private static SimpleRequest getSimpleRequest(HttpServletRequest request) {
        SimpleRequest simpleRequest = new SimpleRequest();
        simpleRequest.setLocalAddr(request.getLocalAddr());
        simpleRequest.setLocalName(request.getLocalName());
        simpleRequest.setMethod(request.getMethod());
        simpleRequest.setPathInfo(request.getPathInfo());
        simpleRequest.setQueryString(request.getQueryString());
        simpleRequest.setRemoteAddr(request.getRemoteAddr());
        simpleRequest.setRemoteHost(request.getRemoteHost());
        simpleRequest.setRemotePort(request.getRemotePort());
        simpleRequest.setRemoteUser(request.getRemoteUser());
        simpleRequest.setRequestURI(request.getRequestURI());
        simpleRequest.setRequestURL(request.getRequestURL().toString());
        return simpleRequest;
    }
}
